import type {Component} from "vue";

export const storeTypeListModules = import.meta.glob('./components/*/storeTypeList.ts', {eager: true})
export const operationComponentModules = import.meta.glob('./components/*/operation/*.vue', {eager: true})

const defaultVersion = 'v1.0.0.0';

/**
 * 获取 合并后的，最新的，storeTypeList.ts
 * 收集components下版本文件夹的storeTypeList, 按照type 获取最新的版本 的 typeConfig;
 * 最终导出页面编辑器左侧面板可用的storeTypeList;
 */
export function getLatestStoreTypeList () {
  const storeTypeMap = new Map();
  const allStoreMap = new Map();
  const relativePaths = Object.keys(storeTypeListModules);
  relativePaths.forEach(relativePath => {
    // 根据文件夹路径获取版本
    const version = relativePath.match(/(?<=\/components\/).+(?=\/storeTypeList\.ts)/)?.[0]

    // 每个版本中保存的导出的组件配置项数组
    const storeTypeList = (storeTypeListModules[relativePath] as any).default

    storeTypeList.forEach((typeConfig: any) => {
      // 为storeType 保存版本
      typeConfig.version = version

      // 存储最新
      if (storeTypeMap.has(typeConfig.type)) {
        const previousStoreType = storeTypeMap.get(typeConfig.type)
        const currentStoreType = typeConfig
        const latestVersion = getLatestVersion(previousStoreType.version, currentStoreType.version);

        if (latestVersion === currentStoreType.version) {
          storeTypeMap.set(currentStoreType.type, currentStoreType);
        }
      } else {
        storeTypeMap.set(typeConfig.type, typeConfig)
      }

      // 存储全部
      allStoreMap.set(typeConfig.type+typeConfig.version, typeConfig)
    })
  })

  console.log("获取到最新的storeTypeList...", [...storeTypeMap.values()]);
  return {
    latestStoreTypeList: [...storeTypeMap.values()],
    allStoreTypeList: [...allStoreMap.values()]
  }
}

export interface IImportedOperationComponentInfo {
  componentName: string;
  component: Component;
  version: string;
}

/**
 * 获取合并后的，去重后的，最新的operation组件
 */
export function getLatestOperationComponents() {
  const operationComponentsMap: Map<string, {version: string, componentName: string, component: Component}> = new Map();
  const relativePaths = Object.keys(operationComponentModules);
  relativePaths.forEach(relativePath => {
    try {
      // relative path
      // e.g. ./components/default/operation/tabsOperation.vue
      // 根据文件夹路径获取版本
      const version = relativePath.match(/(?<=\/components\/).+(?=\/operation)/)?.[0] ?? ''
      // 根据文件夹路径获取组件名
      const componentName = relativePath.match(/(?<=\/operation\/).+(?=\.vue)/)?.[0] ?? ''

      if (!version || !componentName) {
        throw new Error('组件路径不符合规范，请检查' + relativePath);
      }

      // 组件module
      const component = (operationComponentModules[relativePath] as any).default

      if (operationComponentsMap.has(componentName)) {
        const previous = operationComponentsMap.get(componentName)

        // @ts-ignore
        const latestVersion = getLatestVersion(previous.version, version);

        if (latestVersion === version) {
          operationComponentsMap.set(componentName, {
            version,
            componentName,
            component
          });
        }
      } else {
        operationComponentsMap.set(componentName, {
          version,
          componentName,
          component
        });
      }
    } catch (e) {
      console.error(e)
    }
  })
  const operationComponentsWithVersionInfo = [...operationComponentsMap.values()]

  console.log("获取到最新的operationComponents...", operationComponentsWithVersionInfo);
  return operationComponentsWithVersionInfo
}

/**
 * 获取全部版本的operation组件，并且附带版本信息，组件名称
 */
export function getAllOperationComponents (): IImportedOperationComponentInfo[]  {
  const operationComponentsMap: Map<string, IImportedOperationComponentInfo> = new Map();
  const relativePaths = Object.keys(operationComponentModules);
  relativePaths.forEach(relativePath => {
    try {
      // relative path
      // e.g. ./components/default/operation/tabsOperation.vue
      // 根据文件夹路径获取版本
      const version = relativePath.match(/(?<=\/components\/).+(?=\/operation)/)?.[0] ?? ''
      // 根据文件夹路径获取组件名
      const componentName = relativePath.match(/(?<=\/operation\/).+(?=\.vue)/)?.[0] ?? ''

      if (!version || !componentName) {
        throw new Error('组件路径不符合规范，请检查' + relativePath);
      }

      // Vue 组件对象
      const component = (operationComponentModules[relativePath] as any).default

      operationComponentsMap.set(componentName+version, {
        version,
        componentName,
        component, // TODO 优化 异步组件
      });
    } catch (e) {
      console.error(e)
    }
  })

  console.log("获取到全部版本operationComponents...", [...operationComponentsMap.values()]);
  const operationComponentsWithVersionInfo = [...operationComponentsMap.values()]

  return [...operationComponentsWithVersionInfo]
}


/**
 * 比对版本号，获取版本号
 * default文件夹版本会被视为v1.0.0.0
 * @param versions
 */
export function getLatestVersion (...versions: string[]) {
  function getVersionArr (version: string) {
    const versionString = version === 'default' ? defaultVersion : version;
    return versionString.split('v')[1].split('.')
  }

  let latestVersion = versions[0];
  for (let i= 0; i < versions.length; i++) {
    if (!versions[i + 1]) {
      break;
    }
    const currentVersionArr = getVersionArr(versions[i]);
    const nextVersionArr = getVersionArr(versions[i+1]);
    const versionArrLength = Math.max(currentVersionArr.length, nextVersionArr.length)

    for (let j = 0; j < versionArrLength; j++) {
      if (currentVersionArr[j] < nextVersionArr[j]) {
        latestVersion = versions[i + 1]
      }
    }
  }

  return latestVersion
}
